package com.jaya.budan.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaya.budan.R;
import com.jaya.budan.adapter.GV_GeRen_Update_Cover_Adapter;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.bean.ListUser_Information;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.ImageUtils;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.MyGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class GeRen_Update_Msg_Cover_Activity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout back;
    private String access_token, currentUploadPath;
    private LinearLayout ll_update_cover_photo, ll_update_cover_picture;
    private GV_GeRen_Update_Cover_Adapter adapter;
    private MyGridView gv_update_cover;
    private ImageView iv_geren_main_cover;
    private List<ListUser_Information> user_informations;
    private Uri photoUri;
    private static final int TAKE_PHOTO = 0;
    private static final int PICK_PHOTO = 1;
    private static final int RESULT_REQUEST_CODE = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_geren_main_update_cover);
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        back = findViewById(R.id.back);
        iv_geren_main_cover = findViewById(R.id.iv_geren_main_cover);
        gv_update_cover = findViewById(R.id.gv_update_cover);
        ll_update_cover_photo = findViewById(R.id.ll_update_cover_photo);
        ll_update_cover_picture = findViewById(R.id.ll_update_cover_picture);
        back.setOnClickListener(this);
        ll_update_cover_photo.setOnClickListener(this);
        ll_update_cover_picture.setOnClickListener(this);
        gv_update_cover.setHorizontalSpacing(15);
        gv_update_cover.setVerticalSpacing(15);
        // android 7.0系统解决拍照的问题
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
        postData();
        gv_update_cover.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                //判断ListView是否滑动到第一个Item的顶部
                if (view.getChildCount() > 0 && view.getFirstVisiblePosition() == 0 && view.getChildAt(0).getTop() >= view.getPaddingTop()) {
                    //解决滑动冲突，当滑动到第一个item，下拉刷新才起作用
                } else {

                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        gv_update_cover.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ToolUtils.showToast(GeRen_Update_Msg_Cover_Activity.this, user_informations.get(position).getName());
                adapter.setSelect(position);
                adapter.notifyDataSetChanged();
                JSONObject object = new JSONObject();
                try {
                    object.put("type", "background");//封面
                    object.put("path", user_informations.get(position).getReal_path() + "");
                    object.put("p_id", 0);
                    object.put("sort", 1);
                    object.put("b_id", user_informations.get(position).getId() + "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                postCommitData(object);
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_update_cover_photo:
                if (ContextCompat.checkSelfPermission(GeRen_Update_Msg_Cover_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(GeRen_Update_Msg_Cover_Activity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    openAlbum();
                }
                break;
            case R.id.ll_update_cover_picture:
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    //只是加了一个uri作为地址传入
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    try {
                        File photoFile = createImgFile();
                        photoUri = Uri.fromFile(photoFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    cropPhoto(photoUri);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);//指定了存储的路径的uri，那么返回的data就为null
                    startActivityForResult(intent, TAKE_PHOTO);
                } else {
                    ToolUtils.showToast(this, "SD卡不可用~");
                }
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    //获取权限的结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1){
            if (grantResults.length>0&&grantResults[0] == PackageManager.PERMISSION_GRANTED) openAlbum();
            else ToolUtils.showToast(GeRen_Update_Msg_Cover_Activity.this,"你拒绝了");
        }
    }

    /**
     * 自定义图片名，获取照片的file
     */
    private File createImgFile() throws IOException {
        //创建文件
        String fileName = "img_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg";//确定文件名
        File dir;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            dir = Environment.getExternalStorageDirectory();
            dir = getExternalCacheDir();
        } else {
            dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        File tempFile = new File(dir.getPath(), fileName);
        if (tempFile.exists()) {
            tempFile.delete();
        }
        tempFile.createNewFile();
        //获取文件路径
        currentUploadPath = tempFile.getAbsolutePath();
        return tempFile;
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, PICK_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data!=null) {
            switch (requestCode) {
                case TAKE_PHOTO:
                    galleryAddPic();
                    break;
                case PICK_PHOTO:
                    if (Build.VERSION.SDK_INT>=19)
                        handImage(data);
                    else handImageLow(data);
                    break;
                case RESULT_REQUEST_CODE:
                    Log.d("fill", "111" + currentUploadPath);
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        Bitmap head = extras.getParcelable("data");
                        Bitmap bitmap = BitmapFactory.decodeFile(currentUploadPath);
                        iv_geren_main_cover.setImageBitmap(bitmap);
                        JSONObject object = new JSONObject();
                        try {
                            object.put("type", "background");//封面
                            object.put("path", currentUploadPath);
                            object.put("p_id", 0);
                            object.put("sort", 1);
                            object.put("b_id", 1);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        postCommitData(object);
                        if (head != null) {
                            iv_geren_main_cover.setImageBitmap(head);//按钮加载图片
                            ImageUtils.bitmapToBase64(head);//base64加密
                            try {
                                ImageUtils.saveBitmapToFile(head, currentUploadPath);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 调用系统的裁剪
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
//        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.putExtra("crop", "true");
//        intent.putExtra("scale", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    //将图片添加进手机相册
    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(photoUri);
        this.sendBroadcast(mediaScanIntent);
    }

    /**
     * 网络请求
     */
    private void postData() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.main_User_Params_Url + access_token, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("xinyun", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 200) {
                        Gson gson = new Gson();
                        JSONArray info = jsonObject.getJSONArray("info");
                        user_informations = gson.fromJson(info.toString(), new TypeToken<List<ListUser_Information>>(){}.getType());
                        adapter = new GV_GeRen_Update_Cover_Adapter(GeRen_Update_Msg_Cover_Activity.this, user_informations);
                        gv_update_cover.setAdapter(adapter);
                    } else {
                        ToolUtils.showToast(GeRen_Update_Msg_Cover_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(GeRen_Update_Msg_Cover_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    /**
     * 网络请求
     */
    private void postCommitData(JSONObject object) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.fill_information_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("xinyun", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        String path = info.getString("path");
                        Glide.with(GeRen_Update_Msg_Cover_Activity.this).load(path).apply(new RequestOptions()
                                .placeholder(R.mipmap.banner).error(R.mipmap.banner)
                                .diskCacheStrategy(DiskCacheStrategy.NONE)//关闭Glide的硬盘缓存机制
                        ).into(iv_geren_main_cover);
                    } else {
                        ToolUtils.showToast(GeRen_Update_Msg_Cover_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(GeRen_Update_Msg_Cover_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    //安卓版本大于4.4的处理方法
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handImage(Intent data){
        String path =null;
        Uri uri = data.getData();
        //根据不同的uri进行不同的解析
        if (DocumentsContract.isDocumentUri(this,uri)){
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID+"="+id;
                path = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                path = getImagePath(contentUri,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            path = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            path = uri.getPath();
        }
        //展示图片
        displayImage(path);
    }

    //安卓小于4.4的处理方法
    private void handImageLow(Intent data){
        Uri uri = data.getData();
        String path = getImagePath(uri,null);
        displayImage(path);
    }

    //content类型的uri获取图片路径的方法
    private String getImagePath(Uri uri,String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if (cursor!=null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    //根据路径展示图片的方法
    private void displayImage(String imagePath){
        if (imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            JSONObject object = new JSONObject();
            try {
                object.put("type", "background");//封面
                object.put("path", imagePath);
                object.put("p_id", 0);
                object.put("sort", 1);
                object.put("b_id", 1);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            postCommitData(object);
            iv_geren_main_cover.setImageBitmap(bitmap);
        } else {
            ToolUtils.showToast(this, "图片设置失败");
        }
    }
}
